<template>
  <base-modal :title="title" :show.sync="visible" width="820px" class="base-import-modal" @closed="reset">
    <el-form label-position="top" ref="form" :model="form" >

      <el-form-item :label="$t('common.base.rulerName')" :error="formValidationResult.ruleName" required>
        <el-input v-model="form.ruleName" @change="validate" :placeholder="`[${$t('common.placeholder.limitInput', {limit: 20})}]`" :maxlength="20"></el-input>
      </el-form-item>
      <el-form-item :label="$t('common.base.rulerTip')" :error="formValidationResult.ruleDesc" required>
        <el-input v-model="form.ruleDesc" @change="validate" type="textarea" :placeholder="`[${$t('common.placeholder.limitInput', {limit: 500})}]`" :maxlength="500"></el-input>
      </el-form-item>
      <el-form-item :label="$t('common.base.type')" style="margin-bottom: 0px!important;">
        <el-radio-group v-model="form.ruleType" @change="changeRuleType">
          <el-radio :label="0">{{$t('performance.label.scoreRule')}}</el-radio>
          <el-radio :label="1">{{$t('performance.label.prizeRule')}}</el-radio>
        </el-radio-group>
      </el-form-item>
      <el-form-item :label="$t('common.base.ruleContent')">
        {{$t('performance.label.byTaskFinishedNum')}}
      </el-form-item>

      <el-form-item :label="$t('performance.label.calculationMethod')" v-if="form.ruleType">
        <el-select v-model="form.rewardType" @change="validate" :placeholder="$t('common.placeholder.select')">
          <el-option
            v-for="(item, index) in calculations"
            :key="`${item.value}_${index}`"
            :label="item.label"
            :value="item.value">
          </el-option>
        </el-select>
      </el-form-item>

      <el-form-item :label="$t('performance.label.effectCondition')" class="base-condition-wrap">
        <el-select v-model="form.effectCondition" @change="changeEffectCondition" :placeholder="$t('common.placeholder.select')">
          <el-option
            v-for="(item, index) in includeTypes"
            :key="`${item.value}_${index}`"
            :label="item.label"
            :value="item.value">
          </el-option>
        </el-select>

        <span class="ordinary-text" v-if="form.effectCondition"></span>
        <el-select v-model="form.category" v-if="form.effectCondition" :class="{'input-is-error': formValidationResult.category}" @change="changeCategory" :placeholder="$t('common.placeholder.select')">
          <el-option
            v-for="(item, index) in categories"
            :key="`${item.value}_${index}`"
            :label="item.label"
            :value="item.value">
          </el-option>
        </el-select>
      </el-form-item>
      <el-form-item class="base-condition-wrap">
        <!-- TODO 国际化待办，拼接问题待翻译 -->
        <div v-if="!form.effectCondition" class="special-condition-wrap" >
          <span class="ordinary-text" style="padding-left: 0;padding-right: 20px;">负责人{{conditionConfig.label}}</span>
          <el-tooltip :content="conditionConfig.tip" placement="top" effect="light">
            <el-input v-model="form.rules[0].executorScore" @change="validate" :class="{'input-is-error': formValidationResult.rules[0].fields.some(v => v === 'executorScore')}" class="count-input" :placeholder="$t('common.placeholder.inputContent')"></el-input>
          </el-tooltip>
          <span class="ordinary-text">{{conditionConfig.unit}}</span>
          <span class="ordinary-text">协同人{{conditionConfig.label}}</span>
          <el-tooltip :content="conditionConfig.tip" placement="top" effect="light">
            <el-input v-model="form.rules[0].assistantScore" @change="validate" :class="{'input-is-error': formValidationResult.rules[0].fields.some(v => v === 'assistantScore')}" class="count-input" :placeholder="$t('common.placeholder.inputContent')"></el-input>
          </el-tooltip>
          <span class="ordinary-text">{{conditionConfig.unit}}</span>
        </div>
      </el-form-item>

      <el-form-item class="base-condition-wrap">
        <el-select v-model="form.custFieldOfTask" :class="{'input-is-error': formValidationResult.custFieldOfTask}" @change="changeCustFieldOfTask" v-if="form.category === 'customizedFields'" :placeholder="$t('common.placeholder.select')">
          <el-option
            v-for="(item, index) in taskTypes"
            :key="`${item.value}_${index}`"
            :label="item.label"
            :value="item.value">
          </el-option>
        </el-select>
        <span class="ordinary-text" v-if="form.custFieldOfTask"></span>
        <el-select v-model="form.customizedField" :class="{'input-is-error': formValidationResult.customizedField}" v-if="form.custFieldOfTask" @change="changeCustomizedField" :disabled="!taskSelectFields.length" :placeholder="$t('common.placeholder.select')">
          <el-option
            v-for="(item, index) in taskSelectFields"
            :key="`${item.value}_${index}`"
            :label="item.label"
            :value="item.value">
          </el-option>
        </el-select>
        <span class="warning" style="padding-left: 10px" v-if="form.category === 'customizedFields'">{{$t('performance.tip.onlySupportSingleField')}}</span>

      </el-form-item>

      <el-form-item>
        <el-checkbox v-model="form.mark">{{$t('performance.tip.executorRepeatTip')}}</el-checkbox>
      </el-form-item>

      <el-form-item v-if="warning">
        <span class="warning">{{warning}}</span>
      </el-form-item>
      <div v-if="conditionVisible" class="condition-wrap">
        <specific-condition
          v-for="(item, index) in form.rules"
          :item="item"
          :key="index"
          :label="form.effectCondition !== 2 ?`${$t('common.base.condition')}${index+1}` : $t('performance.label.excludeCondition')"
          :rules="form.rules"
          :config="conditionConfig"
          :validation="formValidationResult.rules"
          :field="field"
          @delete-condition="modifyCondition"
          @update="updateCondition"
          :options="options" />

        <base-button v-if="form.effectCondition !== 2" type="only-text" @event="modifyCondition({action: 'add', })">{{$t('common.form.preview.select.addCondition')}}</base-button>
      </div>

    </el-form>
    <div class="dialog-footer">
      <el-button @click="visible = false">{{$t('common.base.cancel')}}</el-button>
      <el-button type="primary" @click="onSubmit" :disabled="pending">{{$t('common.base.confirm')}}</el-button>
    </div>
  </base-modal>
</template>

<script>
import {createPerformanceRule, getFieldsForPerformance, updatePerformanceRule} from '@src/api/PerformanceApi';
import SpecificCondition from './SpecificCondition.vue';
import { t } from '@src/locales';
/* enum */
import { FieldTypeMappingEnum } from '@model/enum/FieldMappingEnum'
export default {
  name: 'setting-rule-dialog',
  props: {
    allTypes: {
      type: Object,
      default: () => ({})
    },
  },
  data() {
    return {
      visible: false,
      pending: false,
      submitted: false,
      performanceRule: {},
      warning: '',
      includeTypes: [
        {
          label: t('common.base.all'),
          value: 0
        },
        {
          label: t('performance.label.onlyInclude'),
          value: 1
        },
        {
          label: t('performance.label.onlyExclude'),
          value: 2
        }
      ],
      calculations: [
        {
          label: t('performance.label.byTaskNum'),
          value: 'amount'
        },
        {
          label: t('performance.label.byTaskProfit'),
          value: 'profit'
        },
        {
          label: t('performance.label.byTaskSale'),
          value: 'sale'
        },
        {
          label: t('performance.label.byTaskSparePartSale'),
          value: 'sparePartSale'
        },
        {
          label: t('performance.label.byTaskSparePartProfit'),
          value: 'sparePartProfit'
        },
        {
          label: t('performance.label.byTaskServiceSale'),
          value: 'serviceSale'
        },
        {
          label: t('performance.label.byTaskServiceProfit'),
          value: 'serviceProfit'
        },
      ],
      categories: [
        {
          label: t('common.label.taskTemplate'),
          value: 'taskTypes',
        },
        {
          label: t('common.form.type.serviceType'),
          value: 'serviceTypes',
        },
        {
          label: t('common.form.type.serviceContent'),
          value: 'serviceContents',
        },
        {
          label: t('performance.label.taskCustomizedFields'),
          value: 'customizedFields',
        },
      ],
      allTaskSelectFields: {},
      taskSelectFields: [],
      form: {
        ruleName: '',
        ruleDesc: '',
        ruleType: 0,
        effect: 1, // 是否启用
        rewardType: 'profit', // 计算方式
        effectCondition: 0, // 生效条件
        category: '', // 工单类型、服务类型、服务内容或者 自定义字段
        custFieldOfTask: '',
        customizedField: '',
        mark: true,
        rules: [
          {
            types: [],
            executorScore: 0,
            assistantScore: 0,
          },
        ],
      },
      formValidation: {
        ruleName(form) {
          let val = form.ruleName;
          if (val) return { field: 'ruleName', value: val, status: 0};
          return {
            field: 'ruleName',
            value: val,
            status: 1,
            msg: t('common.base.isRequire'),
          }
        },
        ruleDesc(form) {
          let val = form.ruleDesc;
          if (val) return { field: 'ruleDesc', value: val, status: 0};
          return {
            field: 'ruleDesc',
            value: val,
            status: 1,
            msg: t('common.base.isRequire'),
          }
        },
        category(form) {
          const {effectCondition, category, } = form;
          if (!effectCondition) return { field: 'category', value: category, status: 0};
          if (category) return { field: 'category', value: category, status: 0};
          return {
            field: 'category',
            value: category,
            status: 1,
            msg: t('common.base.required'),
          }
        },
        custFieldOfTask(form) {
          const {custFieldOfTask, category, } = form;
          if (category !== 'customizedFields') return { field: 'custFieldOfTask', value: custFieldOfTask, status: 0};
          if (custFieldOfTask) return { field: 'custFieldOfTask', value: custFieldOfTask, status: 0};
          return {
            field: 'custFieldOfTask',
            value: custFieldOfTask,
            status: 1,
            msg: t('common.base.required'),
          }
        },
        customizedField(form) {
          const {custFieldOfTask, category, customizedField} = form;
          if (category !== 'customizedFields') return { field: 'customizedField', value: customizedField, status: 0};
          if (!custFieldOfTask) return { field: 'customizedField', value: customizedField, status: 0};
          if (customizedField) return { field: 'customizedField', value: customizedField, status: 0};
          return {
            field: 'customizedField',
            value: customizedField,
            status: 1,
            msg: t('common.base.required'),
          }
        },
        rules(form) {
          const rules = form.rules;

          return rules.map(rule => {
            const {ruleType, effectCondition, rewardType, } = form;
            let errFields = [];
            let executorScore = Number(rule.executorScore);
            let assistantScore = Number(rule.assistantScore);

            if (!ruleType) {
              // 计分制
              if (effectCondition && (!rule.types || !rule.types.length)) {
                // 部分生效 验证 选择类型
                errFields.push('types');
              }
              if (isNaN(executorScore) || typeof executorScore !== 'number' || executorScore < 0 || executorScore > 9999 || (/\./g.test(executorScore) && executorScore.toString().split('.')[1].length > 1)) {
                errFields.push('executorScore');
              }

              if (isNaN(assistantScore) || typeof assistantScore !== 'number' || assistantScore < 0 || assistantScore > 9999 || (/\./g.test(assistantScore) && assistantScore.toString().split('.')[1].length > 1)) {
                errFields.push('assistantScore');
              }
              if (errFields.length) {
                return {
                  status: 1,
                  msg: t('performance.tip.fillWarning'),
                  fields: errFields,
                }
              }
              return {status: 0, fields: []};
            }

            // 奖金 全部生效
            if (effectCondition && (!rule.types || !rule.types.length)) {
              // 部分生效 验证 选择类型
              errFields.push('types');
            }

            if (rewardType !== 'amount') {
              // 按百分比计算
              // || executorScore > 100  || assistantScore > 100
              if (isNaN(executorScore) || typeof executorScore !== 'number' || executorScore < 0 || executorScore > 100 || (/\./g.test(executorScore) && executorScore.toString().split('.')[1].length > 1)) {
                errFields.push('executorScore');
              }

              if (isNaN(assistantScore) || typeof assistantScore !== 'number' || assistantScore < 0 || assistantScore > 100 || (/\./g.test(assistantScore) && assistantScore.toString().split('.')[1].length > 1)) {
                errFields.push('assistantScore');
              }

            } else {
              // 按整数计算

              if (isNaN(executorScore) || typeof executorScore !== 'number' || executorScore < 0 || executorScore > 9999 || (/\./g.test(executorScore) && executorScore.toString().split('.')[1].length > 1)) {
                errFields.push('executorScore');
              }

              if (isNaN(assistantScore) || typeof assistantScore !== 'number' || assistantScore < 0 || assistantScore > 9999 || (/\./g.test(assistantScore) && assistantScore.toString().split('.')[1].length > 1)) {
                errFields.push('assistantScore');
              }

              // if (!Number(rule.executorScore) && !Number(rule.assistantScore)) {
              //   errFields.push('executorScore');
              //   errFields.push('assistantScore');
              // }
            }
            if (errFields.length) {
              return {
                status: 1,
                msg: t('performance.tip.fillWarning'),
                fields: errFields,
              }
            }

            return {status: 0, fields: []};
          })
        }
      },
      formValidationResult: {
        ruleName: null,
        ruleDesc: null,
        ruleType: null,
        rewardType: null,
        effectCondition:  null,
        category: null,
        custFieldOfTask: null,
        customizedField: null,
        rules: [{status: 0, fields: []}],
      },

    }
  },
  computed: {
    taskTypes() {
      return this.allTypes.taskTypes || [];
    },
    serviceTypes() {
      return this.allTypes.serviceTypes || [];
    },
    serviceContents() {
      return this.allTypes.serviceContents || [];
    },
    options() {
      const {form, allTypes, } = this;

      if (form.category !== 'customizedFields') {
        return allTypes[form.category] || [];
      }

      if (form.customizedField) {
        return this.taskSelectFields.filter(f => f.value === form.customizedField)[0].dataSource;
      }
      return [];
    },
    conditionVisible() {
      let arr = ['taskTypes', 'serviceTypes', 'serviceContents'];

      if (arr.some(key => key === this.form.category)) {
        return true;
      }
      return !!this.form.customizedField;
    },
    conditionConfig() {
      // TODO 国际化待办，拼接问题待翻译
      const {ruleType, rewardType} = this.form;
      let prefix = '';
      if (this.form.effectCondition === 2) {
        prefix = '排除后';
      }

      // ruleType 0 计分制 1奖金制
      // rewardType

      if (!ruleType) {
        return {
          label: '每单计',
          unit: '分',
          prefix,
          tip: t('performance.tip.inputNum')
        }
      }

      if (rewardType === 'amount') {
        return {
          label: '每单得',
          unit: '元',
          prefix,
          tip: t('performance.tip.inputNum')
        };
      }

      let label = '';


      switch (rewardType) {
      case 'profit':
        label = '毛利的';
        break;
      case 'sale':
        label = '营收的';
        break;
      case 'sparePartSale':
        label = '工单备件营收的';
        break;
      case 'sparePartProfit':
        label = '工单备件毛利的';
        break;
      case 'serviceSale':
        label = '服务项目营收的';
        break;
      case 'serviceProfit':
        label = '服务项目毛利的';
        break;
      default:
        label = '';
        break;
      }

      return {
        label: `每单得${label}`,
        unit: '%',
        prefix,
        tip: t('performance.tip.inputNum2')
      }


    },
    title() {
      return this.performanceRule.id ? t('performance.title.editPerformanceRule') : t('performance.title.addPerformanceRule');
    },
    action() {
      return this.performanceRule.id ? 'edit' : 'create';
    },
    // 工单自定义表单
    field() {
      return this.form.customizedField ? this.taskSelectFields.find(f => f.value === this.form.customizedField) : {};
    }
  },
  methods: {
    onSubmit() {
      this.submitted = true;
      if (!this.validateForm()) return;
      const params = this.buildParam();

      this.pending = true;
      let fn = this.action === 'create' ? createPerformanceRule : updatePerformanceRule;

      fn(params)
        .then(res => {
          this.pending = false;

          if (res.status) {
            return this.$platform.notification({
              title: t('common.base.fail'),
              message: res.message || '',
              type: 'error',
            });
          }

          this.visible = false;
          this.$platform.notification({
            title: this.action === 'create' ? t('common.base.tip.addSuccess') : t('common.base.tip.updateSuccess'),
            type: 'success',
          });

          this.$emit('refresh-rules');
          this.reset();
        })
        .catch(e => console.error('e', e));

    },
    validateForm() {
      let keysOfValidation = Object.keys(this.formValidation);

      let res = keysOfValidation.map(key => {
        const res = this.formValidation[key](this.form);

        this.formValidationResult[key] = res.msg || null;
        if (key !== 'rules') return !res.status;
        this.formValidationResult.rules = res;
        return res.every(r => !r.status);
      });
      return res.every(r => r);
    },
    buildParam() {
      let {
        ruleName,
        ruleDesc,
        ruleType,
        effectCondition,
        rules,
        category,
        customizedField,
        effect,
        rewardType,
        custFieldOfTask,
        mark,
      } = this.form;
      let tv = {};
      let ruleArr = rules.flatMap(rule => {
        if (rule.types.length > 1 && this.field.formType != FieldTypeMappingEnum.Cascader) {
          return rule.types.map(type => ({
            ...rule,
            types: [type]
          }));
        } else {
          return rule;
        }
      });
      console.log('ruleArrruleArr',ruleArr)

      return {
        id: this.performanceRule.id || '',
        ruleName,
        ruleDesc,
        ruleType,
        effectCondition,
        effect,
        mark: Number(!mark),
        ruleContents: ruleArr.map(r => {
          tv = {};
          if (category === 'taskTypes') {
            tv.settleType = 'templateId';
          } else if (category === 'serviceTypes') {
            tv.settleType = 'serviceType';
          } else if (category === 'serviceContents') {
            tv.settleType = 'serviceContent';
          } else if (category === 'customizedFields') {
            tv.settleType = 'customField';
            // tv.customField = custFieldOfTask;
            tv.customFieldValue = customizedField;
            tv.templateId = custFieldOfTask;
            tv.customFieldType = this.field.formType;
          }

          if (ruleType) {
            tv.rewardType = rewardType;
          }

          tv.screenMsg = this.field.formType == FieldTypeMappingEnum.Cascader? JSON.stringify(r.types): r.types[0];
          tv.assPerson = r.assistantScore;
          tv.chargePerson = r.executorScore;

          return tv;
        })
      };
    },
    fetchFields(id) {
      this.form.customizedField = '';
      let selectedTaskType = this.form.custFieldOfTask;
      if (this.allTaskSelectFields[selectedTaskType]) {
        this.taskSelectFields = this.allTaskSelectFields[selectedTaskType]
        return Promise.resolve(this.taskSelectFields);
      }

      return getFieldsForPerformance(id)
        .then(({succ, data}) => {
          if (succ) {
            this.taskSelectFields = data
              .filter(({formType, setting}) => (formType === 'select' || formType === FieldTypeMappingEnum.Cascader) && setting && !setting.isMulti)
              .map(({displayName, fieldName, setting, formType, tableName}) => {
                // 显示后缀
                let suffix = tableName === 'task_receipt' ? `（${t('performance.label.receipt')}）` : '';
                let label = displayName + suffix;
                if (formType === FieldTypeMappingEnum.Cascader) {
                  return {
                    label,
                    value: fieldName,
                    formType: formType,
                    setting: setting,
                    dataSource: setting.dataSource,
                  }
                }

                return {
                  label,
                  value: fieldName,
                  dataSource: setting.dataSource.map(op => ({
                    label: op,
                    value: op,
                  }))
                }
              });

            return this.allTaskSelectFields[this.form.custFieldOfTask] = this.taskSelectFields;
          }

          return this.taskSelectFields = [];
        })
        .catch(e => console.error('e', e));
    },
    updateCondition({index, newVal, }) {
      this.form.rules[index] = newVal;
      let { rules, } = this.form;

      this.$set(this.form, 'rules', [...rules.map((e, i) => {
        if (i === index) return newVal;
        return e;
      })]);

      this.validate();
    },

    modifyCondition({action, index }) {
      let { rules, } = this.form;
      let { rules: result, } = this.formValidationResult;
      if (action === 'add') {
        this.$set(this.form, 'rules', [...rules, {
          types: [],
          executorScore: 0,
          assistantScore: 0,
        }]);
        this.$set(this.formValidationResult, 'rules', [...result, {
          status: 0, fields: [],
        }]);
      } else {
        this.$set(this.form, 'rules', [...rules.filter((e, i) => i !== index)]);
        this.$set(this.form, 'formValidationResult', [...rules.filter((e, i) => i !== index)]);
      }

      this.validate();
    },
    toggleDialog(pr) {
      this.visible = !this.visible;
      // edit
      if (this.visible && pr) {

        this.performanceRule = pr;

        this.transferRuleToForm();
      }
    },
    transferRuleToForm() {
      const {ruleName, ruleDesc, ruleType, effect, effectCondition, ruleContent, mark} = this.performanceRule;
      const {settleType, templateId, customFieldValue, rewardType} = ruleContent[0];
      let newRules = [];

      // 把负责人、协调人分值相同的条件合并
      ruleContent.forEach(singleRule => {

        if (singleRule.customFieldType == FieldTypeMappingEnum.Cascader || newRules.every(nr => (nr.assPerson !== singleRule.assPerson) || (nr.chargePerson !== singleRule.chargePerson))) {
          newRules.push(singleRule);
        } else {
          newRules = newRules.map(nr => {
            if (nr.assPerson === singleRule.assPerson && nr.chargePerson === singleRule.chargePerson) {
              return {
                assPerson: nr.assPerson,
                chargePerson: nr.chargePerson,
                settleType: nr.settleType,
                screenMsg: `${nr.screenMsg},${singleRule.screenMsg}`
              }
            }
            return nr
          })
        }
        });

      this.form = {
        ruleName,
        ruleDesc,
        ruleType,
        effect, // 是否启用
        rewardType: rewardType || 'profit',
        effectCondition: effectCondition || 0,
        category: '', // 工单类型、服务类型、服务内容或者 自定义字段
        custFieldOfTask: '',
        customizedField: '',
        mark: !mark,
        rules: newRules.map(({assPerson, chargePerson, screenMsg, customFieldType}, index) => {
          let types = screenMsg ? (customFieldType !== FieldTypeMappingEnum.Cascader ? screenMsg.split(',') : JSON.parse(screenMsg)) : [];
          return {
            types,
            assistantScore: assPerson,
            executorScore: chargePerson,
            ...(customFieldType && {customFieldType})
          }
        }),
      };

      if (settleType === 'templateId') {
        this.form.category = 'taskTypes';
        // 把选中的工单类型中被删除的过滤掉
        this.form.rules = this.form.rules.map(condition => {
          condition.types = condition.types.filter(t => this.taskTypes.some(template => template.value === t));

          if (!condition.types.length) {
            condition.placeHolder = t('performance.tip.taskTypeIsDeleted');
            this.warning = t('performance.tip.taskTypeIsDeleted2');
          }

          return condition
        })
        // .filter(condition => condition.types.length)
      }

      if (settleType === 'serviceType') {
        this.form.category = 'serviceTypes';
        // this.form.rules = this.form.rules.map(condition => {
        //   condition.types = condition.types.filter(t => this.serviceTypes.some(template => template.value === t))
        //   return condition
        // })
      }

      if (settleType === 'serviceContent') {
        this.form.category = 'serviceContents';
        // this.form.rules = this.form.rules.map(condition => {
        //   condition.types = condition.types.filter(t => this.serviceContents.some(template => template.value === t))
        //   return condition
        // })
      }

      if (settleType === 'customField') {
        this.form.category = 'customizedFields';
        this.form.custFieldOfTask = templateId;
        // 工单被删除， 把工单往下的值清空
        if (this.taskTypes.every(t => t.value !== templateId)) {
          this.warning = t('performance.tip.taskTypeIsDeleted2');
          return this.changeCategory();
        }

        // 选项被删除
        if (!templateId) return;
        this.fetchFields(templateId)
          .then((res) => {
            let selectedField = res.filter(field => field.value === customFieldValue) || [];

            if (res.length && selectedField.length) {
              // 处理选项被删除的情况
              this.form.rules = this.form.rules.map(rule => {
                // 把被删除的选项过滤掉
                if(rule.customFieldType !== FieldTypeMappingEnum.Cascader){
                  rule.types = rule.types.filter(type => selectedField[0].dataSource.some(option => option.value === type));
                }
                if (!rule.types.length) {
                  this.warning = t('performance.tip.fieldOptionIsDeleted');
                }
                // rule.placeHolder = '选项已被删除请重选';
                return rule;
              });

              return this.form.customizedField = customFieldValue;
            }
            this.warning = t('performance.tip.fieldIsDeleted');
            // res 是条件被选中的字段，如果长度为0就是选中的字段被删除了， reset
            this.clearSomeFieldsVal(['rules', 'customizedField']);
          })
          .catch(err => console.error(err))
      }
      this.formValidationResult.rules = newRules.map(() => ({
        status: 0,
        fields: [],
      }));
    },
    // input change event
    validate() {
      if (this.submitted) {
        this.validateForm();
      }
    },
    changeCustomizedField() {
      this.clearSomeFieldsVal(['rules']);
      this.validate();
    },
    changeCustFieldOfTask() {
      this.fetchFields(this.form.custFieldOfTask);

      this.clearSomeFieldsVal(['rules', 'customizedField']);
      this.validate();
    },
    changeRuleType() {
      let fields = ['category', 'custFieldOfTask', 'customizedField', 'rules', 'rewardType', 'effectCondition'];
      this.clearSomeFieldsVal(fields);

      this.validate();
    },
    changeCategory() {
      let fields = ['rules', 'custFieldOfTask', 'customizedField'];
      this.clearSomeFieldsVal(fields);
      this.validate();
    },
    changeEffectCondition() {
      let fields = ['category', 'custFieldOfTask', 'customizedField', 'rules'];
      this.clearSomeFieldsVal(fields);
      this.clearSomeFieldsVal(fields);
    },
    // clear val
    reset() {
      this.clearSomeFieldsVal(['ruleName', 'ruleDesc', 'category', 'custFieldOfTask', 'customizedField', 'effectCondition', 'ruleType', 'rewardType', 'rules', 'mark']);
      this.performanceRule = {};
      this.submitted = false;
      this.warning = '';
      this.formValidationResult = {
        ruleName: null,
        ruleDesc: null,
        ruleType: null,
        rewardType: null,
        effectCondition:  null,
        category: null,
        custFieldOfTask: null,
        customizedField: null,
        rules: [{status: 0, fields: []}],
      };
    },
    clearSomeFieldsVal(fields) {
      let defaultValIsEmptyString = ['ruleName', 'ruleDesc', 'category', 'custFieldOfTask', 'customizedField'];
      let defaultValIsZero = ['effectCondition', 'ruleType'];
      let key = null;

      for (let i = 0;i <= fields.length;i++) {
        key = fields[i];
        if (key === 'rewardType') {
          this.form[key] = 'profit';
          continue;
        }

        if (key === 'mark') {
          this.form.mark = true;
        }

        if (key === 'rules') {
          this.$set(this.form, 'rules', [{
            types: [],
            executorScore: 0,
            assistantScore: 0,
          }]);
          this.$set(this.formValidationResult, 'rules', [{
            status: 0, fields: [],
          }]);
          continue;
        }

        if (defaultValIsZero.indexOf(key) !== -1) {
          this.form[key] = 0;
          continue;
        }

        if (defaultValIsEmptyString.indexOf(key) !== -1) {
          this.form[key] = '';
          continue;
        }
      }

    },
  },
  components: {
    [SpecificCondition.name]: SpecificCondition,
  }
}
</script>

<style lang="scss">


  .el-textarea textarea{
    padding: 5px 10px;
  }
  .el-form-item__error {
    top: auto;
  }

  .el-form-item {
    margin-bottom: 10px!important;
  }

  .el-radio {
    height: 32px;
    line-height: 32px;
  }

  .input-is-error input {
    border-color: #f56c6c;
  }

  .warning {
    color: #f56c6c;
    font-size: 12px;
  }

  .ordinary-text {
    padding: 0 10px;
  }

  .dialog-footer {
    display: flex;
    justify-content: flex-end;
  }

  .base-condition-wrap {
    .el-form-item__content {
      display: flex;
      flex-wrap: wrap;
    }
    .special-condition-wrap {
      .el-input {
        width: 80px;
      }
    }
  }


  .condition-wrap {
    .specific-condition-container {
      border-top: 1px dashed #ccc;
    }

    .specific-condition-container:last-child {
      border-bottom: 1px dashed #ccc;
    }
    .text-button {
      margin-left: -15px;
    }
  }

</style>
